﻿using WWLauncher.Constant;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace WWLauncher.Util
{
    class ImageUtil
    {
        private const string SYSTEM_ITEM = "::{.*}";

        /// <summary>
        /// 图片数组转 BitmapImage
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        public static BitmapImage ByteArrToImage(byte[] array)
        {
            if (array == null) return null;
            using (var ms = new MemoryStream(array))
            {
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality);
                image.StreamSource = ms;
                image.EndInit();
                image.Freeze();

                //var fileName = array.Md5();
                //Save(image, @"z:\Test\" + fileName + ".png");

                return image;
            }
        }
        public static void Save(BitmapImage image, string filePath)
        {
            if (filePath.IsEmpty()) { return; }
            BitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(image));

            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                encoder.Save(fileStream);
            }
        }
        /// <summary>
        /// BitmapImage 转数组
        /// </summary>
        /// <param name="bi"></param>
        /// <returns></returns>
        public static byte[] BitmapImageToByte(BitmapImage bi)
        {
            if (bi == null) return null;
            using (MemoryStream memStream = new MemoryStream())
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bi));
                encoder.Save(memStream);
                return memStream.GetBuffer();
            }
        }
        /// <summary>
        /// 获取BitmapImage的路径
        /// </summary>
        /// <param name="bi"></param>
        /// <returns></returns>
        public static string BitmapImagePath(BitmapImage bi)
        {
            if (bi == null)
                return string.Empty;

            if (bi.UriSource == null)
                return string.Empty;

            return bi.UriSource.AbsoluteUri;
        }
        /// <summary>
        /// byte[]转换成Image
        /// </summary>
        /// <param name="byteArrayIn">二进制图片流</param>
        /// <returns>Image</returns>
        public static Image ByteArrayToImage(byte[] byteArrayIn)
        {
            if (byteArrayIn == null)
                return null;
            using (var ms = new MemoryStream(byteArrayIn))
            {
                var returnImage = Image.FromStream(ms);
                ms.Flush();
                return returnImage;
            }
        }

        /// <summary>
        /// 图片base64 转 BitmapImage
        /// </summary>
        /// <param name="base64"></param>
        /// <returns></returns>
        public static BitmapImage Base64ToBitmapImage(string base64)
        {
            byte[] byteBuffer = Convert.FromBase64String(base64);
            return ByteArrToImage(byteBuffer);
        }

        /// <summary>
        /// 获取文件 icon
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public static BitmapImage GetBitmapIconByPath(string filePath)
        {
            if (filePath.Contains("%windir%"))
            {
                filePath = filePath.Replace("%windir%", Environment.GetEnvironmentVariable("windir"));
            }

            if (File.Exists(filePath) || IsSystemItem(filePath))
            {
                if (IsImage(filePath))
                {
                    //图片
                    return GetThumbnailByFile(filePath, Constants.IconWidth, Constants.IconWidth);
                }
                else
                { //其它文件
                    return FileIcon.GetBitmapImage(filePath);
                }
            }
            else if (Directory.Exists(filePath))
            {

                if ((filePath.IndexOf("\\") == filePath.LastIndexOf("\\")) && filePath.IndexOf("\\") == filePath.Length - 1)
                {
                    //磁盘
                    return ImageUtil.GetBitmapIconByUri(Constants.DefaultDiskImage);
                }
                else
                {
                    //文件夹
                    return ImageUtil.GetBitmapIconByUri(Constants.DefaultDirImage);
                }

            }
            return null;
        }
        public static BitmapImage GetBitmapIconByUri(string imageUrl)
        {
            try
            {
                BitmapImage bitImage = new BitmapImage();
                bitImage.BeginInit();
                bitImage.UriSource = new Uri(imageUrl, UriKind.Absolute);
                bitImage.EndInit();
                bitImage.Freeze();
                return bitImage;
            }
            catch (System.IO.FileNotFoundException)
            {
                return GetBitmapIconByUri(Constants.DefaultBacImage);
            }
            catch (System.IO.DirectoryNotFoundException)
            {
                return GetBitmapIconByUri(Constants.DefaultBacImage);
            }
            catch (Exception)
            {
                return new BitmapImage();
            }
        }

        public static BitmapImage GetBitmapIconByUnknownPath(string path)
        {
            //string base64 = ImageUtil.FileImageToBase64(path, System.Drawing.Imaging.ImageFormat.Png);
            string ext = "";
            if (!IsSystemItem(path))
            {
                ext = System.IO.Path.GetExtension(path).ToLower();
            }

            string iconPath = null;
            if (".lnk".Equals(ext))
            {

                string targetPath = FileUtil.GetTargetPathByLnk(path);
                iconPath = FileUtil.GetIconPathByLnk(path);
                if (targetPath != null)
                {
                    path = targetPath;
                }
            }
            if (iconPath.IsNullOrEmpty())
            {
                iconPath = path;
            }

            return GetBitmapIconByPath(iconPath);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="filePath">需要改变大小的图片位置</param>
        /// <param name="width">缩略图的宽度</param>
        /// <param name="height">缩略图的高度</param>
        /// <returns></returns>
        public static BitmapImage GetThumbnailByFile(string filePath, int width, int height)
        {

            try
            {
                FileInfo file = new FileInfo(filePath);
                if (file.Exists && file.Length > 0
                    && !System.IO.Path.GetExtension(filePath).Contains("psd"))
                {
                    Image img = Image.FromFile(filePath);
                    if (img.Width <= width && img.Height <= height)
                    {
                        return GetBitmapImageByFile(filePath);
                    }
                    else
                    {
                        Bitmap loBmp = new Bitmap(filePath);
                        ImageFormat loFormat = loBmp.RawFormat;

                        decimal lnRatio;
                        int lnNewWidth;
                        int lnNewHeight;
                        if (loBmp.Width > loBmp.Height)
                        {
                            lnRatio = (decimal)width / loBmp.Width;
                            lnNewWidth = width;
                            decimal lnTemp = loBmp.Height * lnRatio;
                            lnNewHeight = (int)lnTemp;
                        }
                        else
                        {
                            lnRatio = (decimal)height / loBmp.Height;
                            lnNewHeight = height;
                            decimal lnTemp = loBmp.Width * lnRatio;
                            lnNewWidth = (int)lnTemp;
                        }
                        Bitmap bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
                        Graphics g = Graphics.FromImage(bmpOut);
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.FillRectangle(System.Drawing.Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
                        g.DrawImage(loBmp, 0, 0, lnNewWidth, lnNewHeight);
                        loBmp.Dispose();
                        string tempPath = Constants.AppDir + "\\temp";
                        if (File.Exists(tempPath))
                        {
                            File.Delete(tempPath);
                        }
                        bmpOut.Save(tempPath, loFormat);
                        BitmapImage bm = GetBitmapImageByFile(tempPath);
                        File.Delete(tempPath);
                        return bm;
                    }
                }
                else
                {
                    return GetBitmapIconByUri(Constants.DefaultImgImage);
                }
            }
            catch (Exception e)
            {
                LogUtil.WriteErrorLog(e, "获取文件缩略图失败!filePath=" + filePath);
                return GetBitmapIconByUri(Constants.DefaultImgImage);
            }

        }


        public static BitmapImage GetBitmapImageByFile(string filePath)
        {
            BitmapImage bmImg = new BitmapImage();
            bmImg.BeginInit();
            bmImg.CacheOption = BitmapCacheOption.OnLoad;
            RenderOptions.SetBitmapScalingMode(bmImg, BitmapScalingMode.HighQuality);
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                bmImg.StreamSource = fs;
                bmImg.EndInit();
                bmImg.Freeze();
            }
            return bmImg;
        }


        /// <summary>
        /// Bitmap to BitmapImage
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        public static BitmapImage BitmapToBitmapImage(Bitmap bitmap)
        {
            return BitmapToBitmapImage(bitmap, null);
        }

        public static BitmapImage BitmapToBitmapImage(Image bitmap, ImageFormat format)
        {
            BitmapImage bitmapImage = new BitmapImage();
            using (MemoryStream ms = new MemoryStream())
            {
                if (format == null)
                {
                    bitmap.Save(ms, bitmap.RawFormat);
                }
                else
                {
                    bitmap.Save(ms, format);
                }
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = ms;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
                bitmapImage.Freeze();
            }
            return bitmapImage;
        }


        public static BitmapImage Bitmap2BitmapImage(Bitmap bitmap)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                BitmapImage bit3 = new BitmapImage();
                bit3.BeginInit();
                bit3.StreamSource = ms;
                bit3.EndInit();
                bit3.Freeze();
                return bit3;
            }
        }


        /// <summary>
        /// 图片文件转base64
        /// </summary>
        /// <param name="imagefilename"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string FileImageToBase64(string imagefilename, ImageFormat format)
        {
            try
            {
                Bitmap bmp = new Bitmap(imagefilename);

                using (MemoryStream ms = new MemoryStream())
                {
                    bmp.Save(ms, format);
                    byte[] arr = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(arr, 0, (int)ms.Length);
                    ms.Close();

                    return Convert.ToBase64String(arr);
                }
            }
            catch (Exception e)
            {
                LogUtil.WriteErrorLog(e, "图片文件转base64失败!Imagefilename=" + imagefilename + ",ImageFormat=" + format);
                return null;
            }
        }

        /// <summary>
        /// 判断文件是否为图片
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static bool IsImage(string path)
        {
            try
            {
                string ext = Path.GetExtension(path);
                if (!string.IsNullOrEmpty(ext))
                {
                    string strExt = Path.GetExtension(path).Substring(1);
                    string suffixs = "bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,webp,avif";
                    string[] suffixArr = suffixs.Split(',');
                    foreach (string suffix in suffixArr)
                    {
                        if (suffix.Equals(strExt, StringComparison.InvariantCultureIgnoreCase))
                        {
                            return true;
                        }
                    }
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }


        /// <summary>
        /// 判断是否为系统项
        /// </summary>
        /// <returns></returns>
        public static bool IsSystemItem(string path)
        {
            return Regex.IsMatch(path, SYSTEM_ITEM);
        }


    }
}
